package com.example.studentregistration.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.studentregistration.mapper.DormBuildingMapper;
import com.example.studentregistration.pojo.DormBuilding;
import com.example.studentregistration.service.DormBuildingService;
import com.example.studentregistration.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Service
public class DormBuildingServiceImpl implements DormBuildingService {

    @Autowired
    private DormBuildingMapper dormBuildingMapper;

    @Override
    public Result<?> insert(DormBuilding building) {
        // 唯一约束：楼号
        DormBuilding exists = dormBuildingMapper.findByBuildingNo(building.getBuildingNo());
        if (exists != null) {
            return Result.fail("楼号已存在");
        }
        if (building.getStatus() == null || building.getStatus().isEmpty()) {
            building.setStatus("启用");
        }
        if (building.getTotalRooms() == null) building.setTotalRooms(0);
        if (building.getTotalBeds() == null) building.setTotalBeds(0);
        if (building.getOccupiedBeds() == null) building.setOccupiedBeds(0);
        int res = dormBuildingMapper.insert(building);
        return res > 0 ? Result.success("添加成功") : Result.fail("添加失败");
    }

    @Override
    public Result<?> update(DormBuilding building) {
        DormBuilding db = dormBuildingMapper.findById(building.getId());
        if (db == null) return Result.fail("楼宇不存在");
        // 如果更新了楼号，校验唯一性
        if (building.getBuildingNo() != null && !building.getBuildingNo().equals(db.getBuildingNo())) {
            DormBuilding exists = dormBuildingMapper.findByBuildingNo(building.getBuildingNo());
            if (exists != null && !exists.getId().equals(building.getId())) {
                return Result.fail("楼号已存在");
            }
        }
        int res = dormBuildingMapper.update(building);
        return res > 0 ? Result.success("修改成功") : Result.fail("修改失败");
    }

    @Override
    public Result<?> delete(Integer id) {
        DormBuilding db = dormBuildingMapper.findById(id);
        if (db == null) return Result.fail("楼宇不存在");
        int res = dormBuildingMapper.delete(id);
        return res > 0 ? Result.success("删除成功") : Result.fail("删除失败");
    }

    @Override
    public int batchDelete(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) return 0;
        return dormBuildingMapper.batchDelete(ids);
    }

    @Override
    public Page queryAll(Integer currentPage, Integer pageSize) {
        Page<DormBuilding> page = PageHelper.startPage(currentPage, pageSize);
        dormBuildingMapper.findAll();
        return page;
    }

    @Override
    public Result<DormBuilding> queryById(Integer id) {
        DormBuilding db = dormBuildingMapper.findById(id);
        return db == null ? Result.fail("楼宇不存在") : Result.success(db);
    }

    @Override
    public Result<DormBuilding> queryByBuildingNo(String buildingNo) {
        DormBuilding db = dormBuildingMapper.findByBuildingNo(buildingNo);
        return db == null ? Result.fail("楼宇不存在") : Result.success(db);
    }

    // 可选：导出楼宇信息
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<DormBuilding> list = dormBuildingMapper.findAll();
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.write(list, true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("宿舍楼栋信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream os = response.getOutputStream();
        writer.flush(os, true);
        writer.close();
        IoUtil.close(os);
    }
}